<template>
  <div class="chat-container">
    <!-- 左侧对话列表 -->
    <div class="chat-sidebar">
      <el-button type="primary" @click="createNewThread" class="new-chat-btn">
        <el-icon><Plus /></el-icon>
        创建新对话
      </el-button>

       <!-- 排序切换器 -->
      <div class="thread-sort-container">
        <span class="thread-sort-label">排序方式:</span>
        <el-switch
          v-model="sortByLastUsed"
          active-text="最后使用时间"
          inactive-text="创建时间"
          @change="fetchThreads"
        />
      </div>

      <div class="thread-list">
        <div
          v-for="thread in threads"
          :key="thread.id"
          :class="['thread-item', { active: currentThreadId === thread.id }]"
        >
          <div class="thread-content" @click="selectThread(thread.id)">
            <el-icon><ChatLineRound /></el-icon>
            <span class="thread-name">{{ thread.name }}</span>
          </div>
          <el-button
            class="delete-btn"
            type="danger"
            size="small"
            @click.stop="deleteThread(thread.id)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <ChatMessage
      :chat-history="chatHistory"
      :is-loading="isLoading"
      :disabled="!currentThreadId"
      @send="handleSendMessage"
    />
  </div>
</template>

<script setup>

import { ref, onMounted , reactive} from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import { Plus, Delete, ChatLineRound } from '@element-plus/icons-vue'
import ChatMessage from "@/components/AI/ChatMessage.vue";
const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})

const workspaceId = ref(null)
const threads = ref([])
const currentThreadId = ref(null)
const chatHistory = ref([])
const isLoading = ref(false)
const sortByLastUsed = ref(false)  // 排序字段

// 解码 Unicode
function decodeUnicode(str) {
  return str.replace(/\\u[\dA-Fa-f]{4}/g, function(match) {
    return String.fromCharCode(parseInt(match.substr(2), 16));
  });
}

// 发送消息函数
const handleSendMessage = async (message) => {
  if (!message.trim() || !currentThreadId.value || isLoading.value) return
  isLoading.value = true

  // 添加用户消息
  chatHistory.value.push({
    role: 'user',
    content: message
  })

  // 创建新的助手消息对象
  const assistantMessage = {
    role: 'assistant',
    content: '',
    sources: []
  }
  chatHistory.value.push(assistantMessage)

  try {
    const response = await fetch(`/backend/api/llm/thread/${currentThreadId.value}/chat/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
      },
      credentials: 'include',
      body: JSON.stringify({ message })
    });

    if (response.body) {
      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        // 解码收到的数据
        const text = decoder.decode(value);
        // 处理收到的数据块
        const lines = text.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const data = JSON.parse(line.slice(6));

              if (data.error) {
                ElMessage.error(data.error);
                continue;
              }

              if (data.textResponse) {
                // 直接使用原始文本
                assistantMessage.content += data.textResponse;

                // 处理 sources
                if (data.sources && Array.isArray(data.sources)) {
                  const newSources = data.sources.filter(source =>
                    !assistantMessage.sources.some(existing => existing.id === source.id)
                  );
                  assistantMessage.sources.push(...newSources);
                }

                // 强制更新视图
                chatHistory.value = [...chatHistory.value];
              }
            } catch (err) {
              console.error('解析消息失败:', err);
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败');
  } finally {
    isLoading.value = false;
  }
}
const fetchWorkspaceId = async () => {
  try {
    const response = await axios.get(`/backend/api/llm/workspace/course/${props.courseId}/`, {
      withCredentials: true
    })
    workspaceId.value = response.data.id
  } catch (error) {
    ElMessage.error('获取工作区ID失败')
  }
}

const fetchThreads = async () => {
  if (!workspaceId.value) {
    ElMessage.warning('工作区ID未加载')
    return
  }
  try {
    const response = await axios.get(`/backend/api/llm/workspace/${workspaceId.value}/threads/`, {
      withCredentials: true,
      params: {
        sort_by: sortByLastUsed.value ? 'last_used_at' : 'created_at'
      }
    })
    threads.value = response.data
  } catch (error) {
    ElMessage.error('获取对话列表失败')
  }
}

const createNewThread = async () => {
  try {
    const { value: threadName } = await ElMessageBox.prompt('请输入对话名称', '创建新对话', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })

    if (!threadName) return

    const response = await axios.post(
      `/backend/api/llm/workspace/${workspaceId.value}/thread/`,
      { name: threadName },
      { withCredentials: true }
    )
    threads.value.push(response.data)
    currentThreadId.value = response.data.id
    chatHistory.value = []
    ElMessage.success('创建新对话成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('创建新对话失败')
    }
  }
}

const deleteThread = async (threadId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`/backend/api/llm/thread/${threadId}/`, {
      withCredentials: true
    })

    threads.value = threads.value.filter(t => t.id !== threadId)
    if (currentThreadId.value === threadId) {
      currentThreadId.value = null
      chatHistory.value = []
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除对话失败')
    }
  }
}

const selectThread = async (threadId) => {
  if (!threadId) return
  currentThreadId.value = threadId
  chatHistory.value = []
  isLoading.value = true

  try {
    const response = await axios.get(`/backend/api/llm/thread/${threadId}/history/`, {
      withCredentials: true
    })
    chatHistory.value = response.data.history || []
  } catch (error) {
    ElMessage.error('获取对话历史失败')
  } finally {
    isLoading.value = false
  }
}

onMounted(async () => {
  await fetchWorkspaceId()
  await fetchThreads()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 75vh;
}

.chat-sidebar {
  width: 300px;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #dcdfe6;
}

.new-chat-btn {
  margin: 10px;
}

.thread-sort-container {
  margin: 0 10px 10px;
  display: flex;
  align-items: center;
}

.thread-sort-label {
  margin-right: 10px;
}

.thread-list {
  flex: 1;
  overflow-y: auto;
}
.thread-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin: 4px;
  border-radius: 4px;
  cursor: pointer;
  justify-content: space-between;
}

.thread-item:hover {
  background-color: #f5f7fa;
}

.thread-item.active {
  background-color: #ecf5ff;
}

.thread-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.thread-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-btn {
  padding: 2px 5px;
  min-height: auto;
}
</style>